package cn.ctyun.ipush.service.impl;

import cn.ctyun.ipush.dao.EmailDao;
import cn.ctyun.ipush.dao.TaskDao;
import cn.ctyun.ipush.model.EmailModel;
import cn.ctyun.ipush.service.EmailService;
import cn.ctyun.ipush.utils.DateUtils;
import cn.ctyun.ipush.vo.EmailVo;
import com.dexcoder.commons.bean.BeanConverter;
import com.dexcoder.commons.utils.UUIDUtils;
import com.dexcoder.dal.build.Criteria;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 16-7-4
 * Time: 上午10:53
 * To change this template use File | Settings | File Templates.
 */
@Service
public class EmailServiceImpl implements EmailService {

    /* 日志对象 */
    private final Logger LOG = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Autowired
    private EmailDao emailDao;

    @Autowired
    private TaskDao taskDao;

    @Override
    public void save(EmailVo emailVo) {
        emailVo.setEmailModelId(UUIDUtils.getUUID32());
        emailVo.setCreateDate(DateUtils.dateToString(new Date()));
        EmailModel emailModel = emailVo.getTargetObject(EmailModel.class);
        //vo中的emailReceivers进行转义
        StringBuffer stringBuffer = new StringBuffer();
        for (String receiver : emailVo.getEmailReceivers()) {
            stringBuffer.append(receiver).append("$");
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        emailModel.setEmailReceiversDb(stringBuffer.toString());
        //保存到数据库中
        save(emailModel);
    }

    @Override
    public void save(EmailModel emailModel) {
        emailModel.setEmailModelId(UUIDUtils.getUUID32());
        emailDao.save(emailModel);
    }

    @Override
    public int delete(String emailId) {
        //判断是否存在引用，是否在task中.如果有引用肯定存在Job，此时不删除；
        if (taskDao.isExistEmailInTask(emailId)) {
            return 0;
        }
        //不存在，删除缓存，数据库记录删除；无引用肯定也不存在对应的Job
        // DBUtils.deleteConnectionCache(dataSourceDao.querySingleResult(dataSourceId));
        //数据库记录软删除
        return emailDao.delete(emailId);
    }

    @Override
    public int update(EmailVo emailVo) {
        if (StringUtils.isEmpty(emailVo.getEmailModelId())) {
            throw new RuntimeException("email 主键ID 不存在");
        }
        //todo 额外处理
        EmailModel emailModel = emailVo.getTargetObject(EmailModel.class);
        EmailModel emailModelDb = querySingleResult(emailModel.getEmailModelId());

        if (emailModel.getEmailName() != null)
            emailModelDb.setEmailName(emailModel.getEmailName());
        if (emailModel.getSmtpServer() != null)
            emailModelDb.setSmtpServer(emailModel.getSmtpServer());
        if (emailModel.getSmtpUser() != null)
            emailModelDb.setSmtpUser(emailModel.getSmtpUser());
        if (emailModel.getSmtpPassword() != null)
            emailModelDb.setSmtpPassword(emailModel.getSmtpPassword());

        if (emailModel.getEmailSender() != null)
            emailModelDb.setEmailSender(emailModel.getEmailSender());

        if (emailModel.getEmailSubject() != null)
            emailModelDb.setEmailContent(emailModel.getEmailSubject());

        if (emailVo.getEmailReceivers() != null) {
            //vo中的receivers进行转义
            StringBuffer stringBuffer = new StringBuffer();
            for (String emailReceiver : emailVo.getEmailReceivers()) {
                stringBuffer.append(emailReceiver).append("$");
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            emailModelDb.setEmailReceiversDb(stringBuffer.toString());
        }
        return emailDao.update(emailModelDb);
    }

    @Override
    public int update(EmailModel emailModel) {
        if (StringUtils.isEmpty(emailModel.getEmailModelId())) {
            throw new RuntimeException("email 主键ID 不存在");
        }
        return emailDao.update(emailModel);
    }

    @Override
    public EmailVo querySingleResultVo(String emailId) {
        EmailModel emailModel = querySingleResult(emailId);
        return emailModel.getTargetObject(EmailVo.class);
    }

    @Override
    public EmailModel querySingleResult(String emailId) {
        return emailDao.querySingleResult(emailId);
    }

    @Override
    public List<EmailModel> queryList(EmailModel emailModel) {
        emailModel.setIsDeleted("0");
        //Criteria criteria = Criteria.select(EmailModel.class).where("createUserid",  new Object[]{ emailModel.getCreateUserid()}).where("and isDeleted", new Object[]{"0"});
        return emailDao.queryList(emailModel);
    }

    @Override
    public List<EmailVo> queryListVo(EmailVo emailVo) {
        List<EmailModel> emailModelList = queryList(emailVo.getTargetObject(EmailModel.class));
        List<EmailVo> emailVoList = BeanConverter.convert(EmailVo.class, emailModelList);
        for (EmailVo emailVo1 : emailVoList) {
            if (emailVo1.getEmailReceiversDb() != null) {
                String[] receiverList = emailVo1.getEmailReceiversDb().split("\\$");
                List<String> receiverListVo = new ArrayList<String>();
                emailVo1.setEmailReceivers(receiverListVo);
                for (String receiver : receiverList) {
                    receiverListVo.add(receiver);
                }
            }
        }
        return emailVoList;
    }

    @Override
    public boolean isExist(EmailVo emailVo) {
        EmailModel emailModel = emailVo.getTargetObject(EmailModel.class);
        if (null == emailDao.querySingleResultByName(emailModel.getEmailName())) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public boolean isExist(EmailModel emailModel) {

        if (null == emailDao.querySingleResultByName(emailModel.getEmailName())) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public List<EmailVo> queryAll() {
        List<EmailModel> emailModelList = emailDao.queryAll(new EmailModel());
        List<EmailVo> emailVoList = BeanConverter.convert(EmailVo.class, emailModelList);
        for (EmailVo emailVo1 : emailVoList) {
            if (emailVo1.getEmailReceiversDb() != null) {
                String[] receiverList = emailVo1.getEmailReceiversDb().split("\\$");
                List<String> receiverListVo = new ArrayList<String>();
                emailVo1.setEmailReceivers(receiverListVo);
                for (String receiver : receiverList) {
                    receiverListVo.add(receiver);
                }
            }
        }
        return emailVoList;
    }

    @Override
    public List<EmailVo> queryListVoByPage(EmailVo emailVo) {
        //分页查询
        int currentPage = emailVo.getCurPage();
        int itemPages = emailVo.getItemsPerPage();
        List<EmailModel> emailModelList = emailDao.queryListByPage(currentPage, itemPages, emailVo);
        List<EmailVo> emailVoList = BeanConverter.convert(EmailVo.class, emailModelList);
        for (EmailVo emailVo1 : emailVoList) {
            if (emailVo1.getEmailReceiversDb() != null) {
                String[] receiverList = emailVo1.getEmailReceiversDb().split("\\$");
                List<String> receiverListVo = new ArrayList<String>();
                emailVo1.setEmailReceivers(receiverListVo);
                for (String receiver : receiverList) {
                    receiverListVo.add(receiver);
                }
            }
        }
        return emailVoList;
    }
}
